package com.hontech.desktoppastacooker.conn

import java.io.IOException

class TTYSerialPort (name: String, baudRate: Int) : SerialPort {

    private val ref: Long

    init {
        ref = open(name, baudRate)
        if (ref < 0) {
            throw IOException("$name $baudRate open fail")
        }
    }

    companion object {

        init {
            System.loadLibrary("bv-serial_port")
        }

        external fun open(name: String, baudRate: Int): Long
        external fun notifyClose(ref: Long)
        external fun close(ref: Long)
        external fun sync(ref: Long): Int
        external fun readBytes(ref: Long, buf: ByteArray): Int
        external fun write(ref: Long, buf: ByteArray)
    }

    override fun close() = close(ref)

    override fun notifyClose() = notifyClose(ref)

    override fun sync(): Int {
        val n = sync(ref)
        if (n < 0) {
            throw IOException("port closed?")
        }
        return n
    }

    override fun readBytes(buf: ByteArray): Int {
        val n = readBytes(ref, buf)
        if (n < 0) {
            throw IOException("port closed?")
        }
        return n
    }

    override fun write(buf: ByteArray) {
        write(ref, buf)
    }
}

